package com.beiing.tianshuai.tianshuai.mine.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.ETicketBean;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.netease.nim.uikit.common.util.log.LogUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * 电子票详情界面
 *
 * @author 杨金达
 * @date 2018-6-15 08:42:57
 */
public class ETicketActivity extends BaseActivity {

    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;

    @BindView(R.id.rl_e_ticket)
    RelativeLayout mRlETicket;

    /**
     * toolbar标题
     */
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTvTitle;

    /**
     * 电子票背景
     */
    @BindView(R.id.e_ticket_bg)
    ImageView mETicketBg;

    /**
     * 电子票标题
     */
    @BindView(R.id.e_ticket_title)
    TextView mETicketTitle;

    /**
     * 电子票主办方
     */
    @BindView(R.id.e_ticket_owner)
    TextView mETicketOwner;

    /**
     * 电子票时间
     */
    @BindView(R.id.e_ticket_time)
    TextView mETicketTime;

    /**
     * 地址
     */
    @BindView(R.id.e_ticket_address)
    TextView mETicketAddress;

    /**
     * 价格
     */
    @BindView(R.id.e_ticket_price)
    TextView mETicketPrice;

    @BindView(R.id.iv_qr_code)
    ImageView mIvQrCode;
    @BindView(R.id.tv_ticket_code)
    TextView mTvTicketCode;
    @BindView(R.id.btn_save_ticket)
    RelativeLayout mBtnSaveTicket;
    @BindView(R.id.btn_to_take_part_in)
    RelativeLayout mBtnToTakePartIn;

    private Unbinder mUnbinder;
    private Context mContext;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_eticket;
    }

    @Override
    protected void init() {
        mUnbinder = ButterKnife.bind(this);
        mContext = this;
        Intent intent = getIntent();
        String oid = intent.getStringExtra("oid");
        initToolbar();
        getETicketInformation(oid);
        initListener();
    }

    private void initToolbar() {
        mToolbarTvTitle.setText("电子票");
        mToolbarIvBack.setVisibility(View.VISIBLE);
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void getETicketInformation(String oid) {
        DisposableObserver<ETicketBean> observer = new DisposableObserver<ETicketBean>() {
            @Override
            public void onNext(@NonNull ETicketBean bean) {
                if (bean.getCode() == 200) {
                    ETicketBean.DataBean data = bean.getData();
                    ETicketBean.DataBean.NumberBean orderBean = data.getNumber();
                    String title = orderBean.getAname();
                    String owner = orderBean.getRname();
                    String address = orderBean.getAddress();
                    //开始时间
                    String actionTime = orderBean.getActionTime();
                    String price = orderBean.getPrice();
                    if (!TextUtils.isEmpty(actionTime)) {
                        mETicketTime.setText(
                                TimeUtils.getDateToString(Long.parseLong(actionTime) * 1000)
                        );
                    } else {
                        mETicketTime.setText("");
                    }
                    String orderNumber = orderBean.getOrderNumber();
                    mETicketTitle.setText(title);
                    mETicketOwner.setText(owner);
                    mETicketAddress.setText(TextUtils.isEmpty(address) ? "未知" : address);
                    mETicketPrice.setText("0".equals(price) ? "免费" : price);

                    char[] bankArray = orderNumber.toCharArray();
                    StringBuilder bankString = new StringBuilder();
                    for (int i = 0; i < bankArray.length; i++) {
                        if (i % 4 == 0 && i > 0) {
                            bankString.append(" ");
                        }
                        bankString.append(bankArray[i]);
                    }
                    mTvTicketCode.setText(bankString.toString());

                    // 获取二维码图片，有的数据cord为空
                    if (data.getNumber().getQrcode() == null) {
                        return;
                    }
                    //获取二维码图片路径
                    String qrCodeName = data.getNumber().getQrcode();
                    if (!TextUtils.isEmpty(qrCodeName)) {
                        mIvQrCode.setVisibility(View.VISIBLE);
                        RequestOptions avatarOptions = new RequestOptions()
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .centerCrop()
                                .placeholder(R.mipmap.default_avatar)
                                .override(90, 90);
                        //使用了新的网络请求开头
                        Glide.with(mContext.getApplicationContext())
                                .load(HttpRequestConstant.MAIN_REQUEST + data.getNumber().getQrcode())
                                .apply(avatarOptions)
                                .into(mIvQrCode);
                        LogUtil.i("ET_qrcode", "二维码" + data.getNumber().getQrcode());
                    } else {
                        mIvQrCode.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                LogUtil.i("++++++++++", e.getMessage());
                showShortText("网络异常" + e);
                LogUtils.e(e.toString(), "=============Request Error==============");
            }

            @Override
            public void onComplete() {

            }
        };
        DataManager.getETicketInformation(oid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    private void initListener() {
        // 保存图片到本地
        mBtnSaveTicket.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                mRlETicket.setDrawingCacheEnabled(true);
                mRlETicket.buildDrawingCache();                                     //启用DrawingCache并创建位图
                Bitmap bitmap = Bitmap.createBitmap(mRlETicket.getDrawingCache());  //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
                mRlETicket.setDrawingCacheEnabled(false);                           //禁用DrawingCahce否则会影响性能
                String dirPath = Environment.getExternalStorageDirectory() + "/TianShuai/天率校园/";
                File dir = new File(dirPath);
                if (!dir.exists()) {
                    if (!dir.mkdirs()) {
                        LogUtils.e("创建文件夹失败", ETicketActivity.class.getName());
                    }
                }
                File file = new File(dirPath, System.currentTimeMillis() + ".jpg");
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    LogUtils.i("图片已保存", "save success");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                try {
                    assert out != null;
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                showShortText("保存已经至" + Environment.getExternalStorageDirectory() + "/TianShuai/天率校园/" + "下");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }
}